package cn.wowjoy.office.base;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.PermissionChecker;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import javax.inject.Inject;

import cn.wowjoy.office.R;
import cn.wowjoy.office.common.widget.MyToast;
import cn.wowjoy.office.data.constant.Constants;
import cn.wowjoy.office.data.remote.ApiException;
import cn.wowjoy.office.data.remote.ERROR;
import cn.wowjoy.office.data.remote.ExceptionEgine;
import cn.wowjoy.office.databinding.ErrorViewBinding;

import cn.wowjoy.office.utils.PreferenceManager;
import gear.yc.com.gearlibrary.rxjava.rxbus.RxBus;

/**
 * Created by Sherily on 2017/8/23.
 * Description: activity with base function
 */
public abstract class BaseActivity<DB extends ViewDataBinding, VM extends BaseViewModel, P extends BasePresenter<VM>>   extends AppCompatActivity {

    @Inject
    PreferenceManager preferenceManager;

    protected DB binding;

    public boolean requestRuntimePermissions(final String[] permissions, final int requestCode) {
        boolean ret = true;
        for (String permission : permissions) {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M)
                ret &= (PermissionChecker.checkSelfPermission(this, permission) == PermissionChecker.PERMISSION_GRANTED);
            else
                ret &= (ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED);
        }
        if (ret) {
            return true;
        }
        boolean rationale = false;
        for (String permission : permissions) {
            rationale |= ActivityCompat.shouldShowRequestPermissionRationale(BaseActivity.this,permission);

        }
        if (rationale) {
            Toast.makeText(this,"请开启权限后使用",Toast.LENGTH_SHORT).show();
//            makePrimaryColorSnackBar(R.string.common_request_permission, Snackbar.LENGTH_INDEFINITE)
//                    .setAction(R.string.common_allow_permission, new View.OnClickListener() {
//                        @Override
//                        public void onClick(View v) {
//                            ActivityCompat.requestPermissions(BaseActivity.this,permissions, requestCode);
//                        }
//                    })
//                    .show();

        } else {
            ActivityCompat.requestPermissions(BaseActivity.this,permissions, requestCode);

        }
        return false;
    }

    /**
     * 显示和隐藏状态栏
     * @param show
     */
    protected void setStatusBarVisible(boolean show) {
        if (show) {
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
        } else {
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_FULLSCREEN);
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);

//        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        RxBus.getInstance().register(this);
        initializeInjector();
        binding = DataBindingUtil.setContentView(this, getLayoutId());
        this.init(savedInstanceState);
        //直接在每个子presenter通过dagger注入的方式进行自动关联viewmodel,activity。


        initBroadCast();
//        StatusBarCompat.compat(this, ContextCompat.getColor(this, R.color.bg_transparent));
//        StatusBarUtils.with(BaseActivity.this)
//                .setColor(getResources().getColor(R.color.noticeText))
//                .init();
        setLight(this, 55);
    }


    private ErrorViewBinding errorViewBinding;

    /**
     * baseActivity中handleException(Exception e,boolean needErrorView):
     *统一处理exception，当needErrorView = true,是，需要在getErrorview中返回承载errorview的布局，
     *目前支持Framelayout，可以覆盖后面的结果页面。当needErrorView = false,用toast的形式提醒错误，401的状态下统一跳转至LoginActivity
     * @param e
     * @param needErrorview
     */
    public void handleException(Throwable e,boolean needErrorview){
        ApiException apiException = ExceptionEgine.handleException(e);
        if (apiException.getCode() == ERROR.UNAUTHORIZED){
            new MyToast(this).showinfo(apiException.getMessage());
            preferenceManager.clearToken();
//            LoginActivity.startAndClearTask(BaseActivity.this);

        } else {
            if (needErrorview){
                createErrorView(apiException);
            } else {

                new MyToast(BaseActivity.this).showinfo(e.getMessage());
            }

        }
    }


    /**
     * 在每个子activity中实现，哪一块区域需要用，就返回哪块，目前只考虑FrameLayout
     * @return
     */
    protected ViewGroup getErrorViewRoot(){

        return  null;
    }

    public DB getBinding(){
        return binding;
    }
    protected void hideSoftInput(){
        InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(binding.getRoot().getWindowToken(), 0);
    }

//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN ) {
//            hideSoftInput();
//            return true;
//        }
//        return super.onKeyDown(keyCode, event);
//    }
    /**
     * 记住，记住，记住，在需要errorview通过 getErrorViewRoot()返回承载errorview的布局，目前支持Framelayout
     * @param e
     */
    private void createErrorView( ApiException e){
        if (null != getErrorViewRoot()){
            removeErrorview();
            hideSoftInput();
            LayoutInflater  inflater =  LayoutInflater.from(getErrorViewRoot().getContext());
            errorViewBinding = DataBindingUtil.inflate(inflater,R.layout.error_view,getErrorViewRoot(),false);
            errorViewBinding.getRoot().setClickable(true);
            switch (e.getCode()){
                case 404:
                    errorViewBinding.errorContent.setCompoundDrawablesWithIntrinsicBounds(0,R.mipmap.error_404,0,0);
                    errorViewBinding.errorContent.setText(e.getMessage());
                    break;
                case 500:
                    errorViewBinding.errorContent.setCompoundDrawablesWithIntrinsicBounds(0,R.mipmap.error_500,0,0);
                    errorViewBinding.errorContent.setText(e.getMessage());
                    break;
                case 1002:
                    errorViewBinding.errorContent.setCompoundDrawablesWithIntrinsicBounds(0,R.mipmap.wi_fi,0,0);
                    errorViewBinding.errorContent.setText(e.getMessage());
                    break;
                default:
                    errorViewBinding.errorContent.setText(e.getMessage());
                    break;
            }
            errorViewBinding.errorContent.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    refreshError();
                }
            });
            ViewGroup.LayoutParams layoutParams = getErrorViewRoot().getLayoutParams();
            getErrorViewRoot().addView(errorViewBinding.getRoot(),layoutParams);
        } else {
            //知道你们会忘记加布局，为了防止异常，有toast提醒
            new MyToast(BaseActivity.this).showinfo(e.getMessage());
        }


    }


    /**
     *在refreshError之后记住removeErroeView
     */
    public void removeErrorview(){

        if (null != getErrorViewRoot()){
            if (null != errorViewBinding)
                getErrorViewRoot().removeView(errorViewBinding.getRoot());
        }
    }

    /**
     * errorView添加后，点击error图片即可重新请求相应的接口，进行处理
     */
    protected void refreshError(){
        removeErrorview();
        //具体页面实现请求对应接口渲染数据
    }

    protected void changeErrorViewContent(int resId, ApiException e){
        errorViewBinding.errorContent.setCompoundDrawablesWithIntrinsicBounds(0,resId,0,0);
        errorViewBinding.errorContent.setText(e.getMessage());
    }


    private IntentFilter intentFilter;
    private ScanReceiver scanReceiver;

    /**
     * 每个页面需要广播时候开启注册广播
     */
    protected void openBroadCast(){
        registerReceiver(scanReceiver, intentFilter);
    }


    /**
     * 取消广播
     */
    protected void closeBroadCast(){
        
        unregisterReceiver(scanReceiver);
    }

    private void initBroadCast(){
        intentFilter = new IntentFilter();
        intentFilter.addAction(Constants.BAR_ADD);
        intentFilter.addAction(Constants.RFID_ADD);
        intentFilter.addAction(Constants.WOW_ADD);
        intentFilter.addAction(Constants.WOW_NEW_ADD);
        scanReceiver = new ScanReceiver();
    }

    class ScanReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Constants.BAR_ADD)) {
                new MyToast(context).showinfo(intent.getStringExtra(Constants.BAR_KEY));
                if (!"ERROR".equals(intent.getStringExtra(Constants.BAR_KEY))) {
                }
            } else if (intent.getAction().equals(Constants.RFID_ADD)) {
                new MyToast(context).showinfo(intent.getStringExtra(Constants.RFID_KEY));
                if (!"ERROR".equals(intent.getStringExtra(Constants.BAR_KEY))) {
                }
            } else if (intent.getAction().equals(Constants.WOW_ADD)) {
//                new MyToast(context).showinfo(intent.getStringExtra(Contants.WOW_KEY));
            } else if (intent.getAction().equals(Constants.WOW_NEW_ADD)) {
                String msg = intent.getStringExtra(Constants.WOW_NEW_KEY);
                brodcast(context, msg);
            }
        }
    }


    /**
     *扫码自定义逻辑
     * @param context
     * @param msg
     */
    protected void brodcast(Context context, String msg) {
        //实现扫码逻辑
    }

    protected abstract void initializeInjector();


    public ApplicationComponent getApplicationComponent() {
        return ((MainApplication) getApplication()).getmApplicationComponent();
    }

    protected abstract void init(Bundle savedInstanceState);

    protected abstract int getLayoutId();


    private void setLight(Activity context, int brightness) {
        WindowManager.LayoutParams lp = context.getWindow().getAttributes();
        lp.screenBrightness = Float.valueOf(brightness) * (1f / 255f);
        context.getWindow().setAttributes(lp);
    }
    @Override
    public void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
    }

    @Override
    protected void onDestroy() {
        if (null != getPresenter()) getPresenter().onDestroy();
        binding.unbind();
        super.onDestroy();
        RxBus.getInstance().unRegister(this);
    }


    protected abstract P getPresenter();
    protected abstract VM getViewModel();

}
